package com.kanqiubao.kq.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.kanqiubao.kq.R;
import com.kanqiubao.kq.activity.BaseActivity;
import com.kanqiubao.kq.http.HttpListener;
import com.kanqiubao.kq.view.EmptyLayout;
import com.superrecycleview.superlibrary.adapter.SuperBaseAdapter;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import okhttp3.Call;


public abstract class BaseFragment<T> extends Fragment implements HttpListener<T> {

    private boolean isVisible = false;//当前Fragment是否可见
    private boolean isInitView = false;//是否与View建立起映射关系
    protected boolean isFirstLoad = true;//是否是第一次加载数据
    protected String mRequestType = "";
    protected String mSearchKey = "";
    protected EmptyLayout mEmptyLayout;
    protected View mSuccessView;
    private String mTitle;
    protected View convertView;
    private SparseArray<View> mViews;

    public BaseFragment() {
        if (getArguments() == null) {
            setArguments(new Bundle());
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (convertView == null) {
            convertView = inflater.inflate(getLayoutId(), container, false);
            mEmptyLayout = (EmptyLayout) convertView.findViewById(R.id.error_layout);
            mSuccessView = convertView.findViewById(R.id.view_holder);
            initEmptyLayout();
            mViews = new SparseArray<>();
            initView();
        }

        return convertView;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        isInitView = true;
        lazyLoadData();
    }

    private BaseActivity<?> mActivity;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mActivity = (BaseActivity<?>) context;
    }

    public BaseActivity getAppBaseActivity() {
        return mActivity;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        if (isVisibleToUser) {
            isVisible = true;
            lazyLoadData();
        } else {
            isVisible = false;
        }
        super.setUserVisibleHint(isVisibleToUser);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
    }

    private void lazyLoadData() {
        if (isFirstLoad && isInitView && (isVisible || getUserVisibleHint())) {
            //第一次加载数据且必须初始化完成视图
            initData();
            isFirstLoad = false;
        } else {
            //已经加载过数据
            if (isInitView && (isVisible || getUserVisibleHint())) {
                //重新恢复数据
                initRecoveryData();
            }
        }
        if (!isFirstLoad || !isVisible || !isInitView) {
//           LogUtils.v("basefragment--->>>不加载" + "   " + this.getClass().getSimpleName());
            return;
        }
    }

    /**
     * 回收view与数据的关系
     */
//    @Override
//    public void onDestroyView() {
//        isInitView = false;
//        LogUtils.v("onDestroyView--->>>" + mRequestType);
//        super.onDestroyView();
//    }

    /**
     * 加载页面布局文件
     *
     * @return
     */
    protected abstract int getLayoutId();

    /**
     * 让布局中的view与fragment中的变量建立起映射
     */
    protected abstract void initView();

    /**
     * 加载要显示的数据
     */
    protected abstract void initData();

    /**
     * 恢复数据，比如第二次回来恢复之前的数据
     */
    protected void initRecoveryData() {
    }

    /**
     * fragment中可以通过这个方法直接找到需要的view，而不需要进行类型强转
     *
     * @param viewId
     * @param <E>
     * @return
     */
    protected <E extends View> E findView(int viewId) {
        if (convertView != null) {
            E view = (E) mViews.get(viewId);
            if (view == null) {
                view = (E) convertView.findViewById(viewId);
                mViews.put(viewId, view);
            }
            return view;
        }
        return null;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // Restore State Here
        if (!restoreStateFromArguments()) {
            // First Time, Initialize something here
            onFirstTimeLaunched();
        }
    }

    /**
     * 首次启动
     */
    protected void onFirstTimeLaunched() {

    }

    private Bundle savedState;

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //保存状态
        saveStateToArguments();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        // Save State Here
        isInitView = false;
        saveStateToArguments();
    }

    /**
     * 保存状态
     */
    private void saveStateToArguments() {
        if (getView() != null)
            savedState = saveState();
        if (savedState != null) {
            Bundle b = getArguments();
            b.putBundle("jmjs_savestate", savedState);
        }
    }

    /**
     * 恢复数据
     *
     * @return
     */

    private boolean restoreStateFromArguments() {
        Bundle b = getArguments();
        savedState = b.getBundle("jmjs_savestate");
        if (savedState != null) {
            restoreState();
            return true;
        }
        return false;
    }

    /**
     * 恢复数据，私有的
     */
    private void restoreState() {
        if (savedState != null) {
            // For Example
            mRequestType = savedState.getString("mRequestType");
            mSearchKey = savedState.getString("mSearchKey");
            onRestoreState(savedState);
        }
    }

    /**
     * 预留子类恢复数据
     *
     * @param savedInstanceState
     */
    protected void onRestoreState(Bundle savedInstanceState) {

    }

    /**
     * 保存数据
     *
     * @return
     */

    private Bundle saveState() {
        Bundle state = new Bundle();
        state.putString("mRequestType", mRequestType);
        state.putString("mSearchKey", mSearchKey);
        onSaveState(state);
        return state;
    }

    /**
     * 预留子类保存
     *
     * @param outState
     */
    protected void onSaveState(Bundle outState) {

    }

    public String getmTitle() {
        return mTitle;
    }

    public void setmTitle(String mTitle) {
        this.mTitle = mTitle;
    }

    public void setmRequestType(String type) {
        this.mRequestType = type;
    }

    public void setmSearchKey(String mSearchKey) {
        this.mSearchKey = mSearchKey;
    }

    public String getmRequestType() {
        return mRequestType;
    }

    protected void shouCustomProgressDialog() {
        if (getActivity() != null) {
            ((BaseActivity<?>) getActivity()).shouCustomProgressDialog();
        }
    }

    protected void dissmisCustomProgressDialog() {
        if (getActivity() != null) {
            ((BaseActivity<?>) getActivity()).dissmisCustomProgressDialog();
        }
    }

    protected void requestData() {
        shouCustomProgressDialog();
    }

    protected void startMyActivity(Class<?> cls) {
        ((BaseActivity<?>) getActivity()).startMyActivity(cls);
    }

    protected void startMyActivity(Intent in, Class<?> cls) {
        ((BaseActivity<?>) getActivity()).startMyActivity(in, cls);
    }

    public void startMyActivity(Intent in) {
        ((BaseActivity<?>) getActivity()).startMyActivity(in);
    }

    public void click(View v) {

    }

    public void error(okhttp3.Response response) {
        dissmisCustomProgressDialog();
        if (getActivity() != null) {
            ((BaseActivity<?>) getActivity()).error(response);
        }
    }

    /**
     * 0,有数据显示 1，没有数据 2,表示网络问题
     *
     * @param type
     */
    protected void isVisableView(int type) {
        if (mEmptyLayout != null) {

            if (type == 0) {
                mEmptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
                mSuccessView.setVisibility(View.VISIBLE);
            } else if (type == 1) {
                mEmptyLayout.setErrorType(EmptyLayout.NODATA_ENABLE_CLICK);
                mSuccessView.setVisibility(View.GONE);
            } else if (type == 2) {
                mEmptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
                mSuccessView.setVisibility(View.GONE);
            } else if (type == 3) {
                mEmptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
                mSuccessView.setVisibility(View.GONE);
            }
        }
    }

    protected void emptyLayoutClick() {
    }

    private void initEmptyLayout() {
        if (mEmptyLayout != null) {
            mEmptyLayout.setOnLayoutClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    emptyLayoutClick();
                }
            });
        }
    }

    public void initRequest() {
    }

    @Override
    public void onSuccess(T paramT, Call paramCall, okhttp3.Response paramResponse) {
//        if (paramResponse.code() != 200) {
        error(paramResponse);
//        }

    }

    @Override
    public void onCacheSuccess(T t, Call call) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onCacheError(Call call, Exception e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void parseError(Call call, Exception e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onAfter(T t, Exception e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onError(Call call, okhttp3.Response response, Exception e) {
        error(response);
    }

}
